﻿$(function () {
    //用于解决ASP.NET MVC中Checkbox的BUG
    $('form').submit(function () {
        $(':checkbox:checked', $(this)).each(function (i, cb) {
            var e = $(cb);
            var hf = $(':hidden[name="' + e.attr('name') + '"]');
            if (hf.length > 0) {
                e.attr('checked', false);
                hf.val('true');
            }
        });
    });
    showResultMessage();
});
//矫正IE中的setTimeout和setInterval、IE 重写setTimeout、setInterval
function resetIETimeoutAndInterval() {
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var _preTimeout = window.setTimeout, _preInterval = window.setInterval;
        window.setTimeout = function (callback, after) {
            var l = arguments.length;
            if (l > 2) {
                var args = [];
                for (var i = 2; i < l; i++) {
                    args.push(arguments[i]);
                }
                return _preTimeout(function () {
                    callback.apply(this, args);
                }, after);
            }
            else {
                return _preTimeout.apply(this, arguments);
            }
        }
        window.setInterval = function (callback, cycle) {
            var l = arguments.length;
            if (l > 2) {
                var args = [];
                for (var i = 2; i < l; i++) {
                    args.push(arguments[i]);
                }
                return _preInterval(function () {
                    callback.apply(this, args);
                }, cycle);
            }
            else {
                return _preInterval.apply(this, arguments);
            }
        }
    }
}
//页面提示信息
function showResultMessage() {
    var resultMsg = $('#__result_msg__').html();
    if ($.trim(resultMsg) != '') {
        alert(resultMsg);
    }
}
//创建富文本编辑框
function createEditor(cId, height, width) {
    var oFCKeditor = new FCKeditor(cId);
    oFCKeditor.Height = (typeof height == "undefined") ? 300 : height;
    oFCKeditor.Width = (typeof width == "undefined") ? 782 : width;
    oFCKeditor.ToolbarSet = 'YeexBoss';
    oFCKeditor.ReplaceTextarea();
    return oFCKeditor;
}
//全选、取消
function checkItems(name) {
    var e = window.event;
    var obj = e.target || e.srcElement;
    $(':checkbox[name="' + name + '"]').attr('checked', $(obj).attr('checked') ? 'checked' : '');
}
//上传文件(cId：上传按钮；fileUrlInput：上传成功后返回路径存放的控件Id；typeNo：上传类型；onClosed：上传完成后的回调函数；uploadType：上传类型。）
/*
    配套预览上传图片效果方法详见showUploadImg
    createUpload(cId, fileUrlInput, typeNo, function(){showUploadImg(fileUrlInput, showDom, finalUrlInp)})
*/
function createUpload(cId, fileUrlInput, typeNo, onClosed, oPathInput, uploadType) {
    if (typeof typeNo == 'undefined' || $.trim(typeNo) == '') {
        typeNo = 'default';
    }
    var url = '?u=' + fileUrlInput;
    if (typeof oPathInput != 'undefined' && $.trim(oPathInput) != '') {
        url += '&o=' + oPathInput;
    }
    if (typeof (uploadType) == 'undefined') {
        url += '&type=html';
    } else {
        url += '&type=swf';
    }
    $('#' + cId).colorbox({
        height: '400px',
        width: '550px',
        href: '/file/upload/' + typeNo + url,
        scrolling: false,
        overlayClose: false,
        iframe: true,
        title: '上传文件',
        onClosed: onClosed
    });
    //绑定删除图片方法
    bindDelImg();
}
/*显示上传图片
    参数说明：(fileUrlInput:上传成功后返回路径存放的控件ID, showDom：显示缩略图的html元素ID, 【finalInp:可选参数,空则新上传图片替换旧有图片，否则图片可继续添加,此input为提交表单时需要的input】)
    编辑页面输出已有图片格式：
    <div id="你定finalUrlInp的ID" class="showImgUrl">
        <span><img src="图片路径"/><a href="?" class="delImg" to="你定finalUrlInp的ID（如不可传多张，则为createUpload方法返回URL的URLinputID）">删除</a></span>
    </div>

*/
function showUploadImg(fileUrlInput, showDom, finalUrlInp) {
    var isMulti = false, $newInp = null, str, arrUrl, oldVal;
    var $oldInp = typeof fileUrlInput == 'String' ? $(fileUrlInput) : fileUrlInput;
    var $show = typeof showDom == 'String' ? $(showDom) : showDom;
    if (finalUrlInp != '' && finalUrlInp != undefined) {
        $newInp = typeof finalUrlInp == 'string' ? $(finalUrlInp) : finalUrlInp;
        isMulti = true;
    }
    //alert($show.length)
    $show.addClass('showImgUrl');
    if ($oldInp.val() != '') {
        arrUrl = $oldInp.val().split(';');
        str = '';
        for (var i = 0; i < arrUrl.length; i++) {
            oldVal = arrUrl[i];
            str += '<span><img src="/' + oldVal + '"/><a href="?" class="delImg" to="' + (isMulti ? $newInp.attr('id') : $oldInp.attr('id')) + '">删除</a></span>';
        }
        if (isMulti) {
            $show.append(str);
            var newVal = $newInp.val() == '' ? '' : $newInp.val() + ',';
            // $newInp.val(newVal + oldVal);    处理~
            $newInp.val(newVal + arrUrl.join(','));
            $oldInp.val('');
        } else {
            $show.html(str);
        }
        //alert($newInp.val())
        $('.delImg', $show).unbind('click').bind('click', delUploadImg);
    }
}
function delUploadImg(e) {
    var $span = $(this).parent();
    var $inp = $('#' + $(this).attr('to'));
    var arr = $inp.val().split(',');
    arr.splice($span.index(), 1);
    $inp.val(arr.join(','));
    $span.remove();
    //alert($inp.val())
    return false;
}
function bindDelImg() {
    $('.showImgUrl .delImg').bind('click', delUploadImg);
}
//获取客户端浏览器版本
function getBrowserVersion() {
    var Sys = {};
    var ua = navigator.userAgent.toLowerCase();
    var s;
    (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
        (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
        (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
        (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
        (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;

    if (Sys.ie) return 'IE ' + Sys.ie;
    if (Sys.firefox) return 'Firefox ' + Sys.firefox;
    if (Sys.chrome) return 'Chrome ' + Sys.chrome;
    if (Sys.opera) return 'Opera ' + Sys.opera;
    if (Sys.safari) return 'Safari ' + Sys.safari;
    return 'Others';
}
//进度条控制
function getProgressStatus(onFinished, data) {
    var url = '/message/status/' + uniqueId;
    $.get(url, function (d) {
        $('#__progress_status_text__').html(d + '%');
        if (parseInt(d) >= 100) {
            $('#__progress_status_border__').hide();
            if (typeof onFinished != 'undefined') {
                onFinished(data);
            }
            return;
        }
        $('#__progress_status_fill__').width(d);
        window.setTimeout(function (a, b) { getProgressStatus(a, b); }, 100, onFinished, data);
    });
}
function showProgressBar(onFinished, data) {
    resetIETimeoutAndInterval();
    if ($('#__progress_status_border__').length == 0) {
        var html = '<div id="__progress_status_border__"><div id="__progress_status_fill__"></div></div>';
        $('body').append(html);
    }
    $('#__progress_status_border__').show();
    getProgressStatus(onFinished, data);
}
//多选选择值
function retCheckBoxVal(A) { var C = ""; var B = $("input[name='" + A + "']:checkbox:checked"); B.each(function () { if ($(this).val() != "") { C += $(this).val() + "," } }); return C }
//textarea统计
function countInput(maxLength, lbName) {
    var inputStr = $("#" + lbName).val();
    if (inputStr != "") {
        var curLength = inputStr.length;
        var yLength = maxLength - curLength;
        if (yLength < 0) {
            $("#" + lbName).val(inputStr.substring(0, maxLength));
        } else {
            $("#aTitle").html("最长" + maxLength + "/余" + yLength + "个字符");
        }
    }
}
//getradioVal
function retRadiVal(a) {
    var sValue;
    $('input[name=' + a + ']').each(function (i, n) {
        if (this.checked) {
            sValue = this.value;
            return;
        }
    })
    return sValue;
}

//获取？号后参数值
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return "";
}

function subajax(url) {
    $.ajax({
        async: false,
        type: 'POST',
        url: url,
        //data: { email: email, type: 1 },
        success: navTabAjaxDone || DWZ.ajaxDone,
        error: DWZ.ajaxError
    });
}
//自动完成
//参数：1--需要自动完成的input，2--后端URL，3--需要保存ID的input，4---显示内容的span(没有则传false或'')，5，自动完成提示框的宽度 
//    6,额外参数*JSON*格式 固定值如{t:val,t2:val2}或者动态获取值则 {t:function(){return $('input').val()}}**动态获取勿忘/return/
function setAutoComp($Input, url, $hideInput, $showSpanOrFalse, width, extraParams) {
    if ($showSpanOrFalse && $showSpanOrFalse != '') {
        $hideInput.showInputContent({ $Span: $showSpanOrFalse, operator: ',', unique: true });
    }
    ep = extraParams == undefined ? {} : extraParams;
    $Input.autocomplete(url, {
        minChars: 1,
        width: width,
        max: 20,
        scrollHeight: 250,
        scroll: true,
        extraParams: ep,
        //noResultCallback:function(){$('body').append('无')},
        formatItem: function (row, i, max) {
            return row.name;
        },
        formatResult: function (row) {
            if (!$showSpanOrFalse) {
                return row.name;
            }
        }
    }).result(function (event, data, formatted) {
        if (data != '' && data != undefined) {
            if ($showSpanOrFalse) {
                $hideInput.showInputContent('addItem', [data.id, data.name]);
            } else {
                $hideInput.val(data.id);
            }
        }
    });
}
/*各后台栏目的js都是给Boss的属性*/
var BOSS = {};
//展开关闭层
/*使用方法$('*[role^="slide-btn"]').click(fnSlideUpDown);
    结构 <div role="slide-area">
            <a role="slide-btn"></a>
            <div role="slide-con"></div>
            <div role="slide-con"></div>...
        </div> 
*/
function fnSlideUpDown(e) {
    var btn = $(this);
    var isTxt = false;
    if (btn.attr('closeTxt') != undefined) {
        isTxt = true;
        var closeTxt = btn.attr('closeTxt'),openTxt = btn.attr('openTxt');
    }
    var area = $(this).parents('*[role="slide-area"]');
    var index = 0;
    if (area.length === 0) { area = $('body') };
    var con;
    if ($(this).attr('slideIndex')) {
        index = $(this).attr('slideIndex');
        con = area.find('*[role="slide-con"][slideIndex="' + index + '"]');
    } else {
        con = area.find('*[role="slide-con"]')
    }
    if (con.is(':hidden')) {
        con.show()
        //con.slideDown();
        btn.addClass('slide-btn-close').removeClass('slide-btn-open');
        if (isTxt) {
            btn.text(closeTxt);
        }
    } else {
        con.hide();
        //con.slideUp();			
        btn.removeClass('slide-btn-close').addClass('slide-btn-open');
        if (isTxt) {
            btn.text(openTxt);
        }
    }
    if ($(this).is('a')) {
        return false;
    }
}
/*
    复制一行表单(如财务-收客人款-快钱-添加订单)

使用方法
    css 结构
        最外层 .J-cloneFormRow
        需要复制的表单行 .J-item  
        添加 .J-add
        删除 .J-del
        计数input .J-count
        在需要重新赋name的表单元素上加Jname属性，最终name值是Jname+当前index+1
        如<input name="inp" Jname="inp">，最终第二行的name则为inp2;
    js
        直接调用fnCloneFormRow()
        或者
        var xxx = new oCloneFormRow();
        xxx.init();
*/

var oCloneFormRow = function (arg) {
    var oThis = this;
    //复制并添加一行
    this.fnAdd = function () {
        var $this = $(this);
        var thisDl = $this.parents('.J-item');
        var $wrap = $this.parents('.J-cloneFormRow:first');
        var newDl = thisDl.clone();
        thisDl.after(newDl);
        oThis.fnOrder($wrap);
        oThis.init();
        return false;
    };
    //排序表单元素name
    this.fnOrder = function ($wrap) {
        var elParent = $wrap;
        var dls = elParent.children('.J-item');
        dls.each(function (i, n) {
            var $this = $(this);
            var index = i + 1;
            var el = $('[Jname]', $this);
            el.each(function () {
                var Jname = $(this).attr('Jname') + index;
                $(this).attr('name', Jname);
            })
        });
        elParent.find('.J-count').val(dls.length);
    };
    //删除当前行
    this.fnDel = function () {
        var $this = $(this);
        var $wrap = $this.parents('.J-cloneFormRow:first');
        alertMsg.confirm('确定删除吗?', { okCall: function () { $this.parents('.J-item').remove(); oThis.fnOrder($wrap); } })
        return false;
    };
    this.init = function () {
        if ($('.J-cloneFormRow').length > 0) {
            $('.J-del', '.J-cloneFormRow').unbind('click').click(oThis.fnDel);
            $('.J-add', '.J-cloneFormRow').unbind('click').click(oThis.fnAdd);
        }
    };
}
//调用复制表单行方法
function fnCloneFormRow() {
    var obj = new oCloneFormRow();
    obj.init();    
}
//通过已知文本设置select所选项
function fnSelectItemByText1(dSel, strText) {
    var dOptions = dSel.options;
    for (var i = 0; i < dOptions.length; i++) {
        //alert(dOptions[i].text + '----' + strText);
        if (dOptions[i].text == strText) {
            //alert(dOptions[i].text + '-' + strText + (dOptions[i].text == strText))
            dOptions[i].selected = true;
            return;
        }
    }
}
//通过已知值找所选项
function fnSelectItemByVal(dSel, val) {
    
    var dOptions = dSel.options;

    for (var i = 0; i < dOptions.length; i++) {
        //alert(dOptions[i].value + '----' + val);
        if (dOptions[i].value == val) {
            dOptions[i].selected = true;
            return;
        }
    }
}

function isNumber(str) {
    if (str == '') {
        return false;
    } else {
        return /^\d+$/.test(str);
    }
}

